package com.foodorder.controller;

import com.foodorder.dto.ApiResponse;
import com.foodorder.dto.LoginRequest;
import com.foodorder.dto.RegisterRequest;
import com.foodorder.entity.User;
import com.foodorder.service.UserService;
import com.foodorder.service.NotificationService;
import com.foodorder.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户认证控制器
 */
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@CrossOrigin(origins = {"http://localhost:3001", "http://localhost:3002"})
public class AuthController {
    
    private final UserService userService;
    private final NotificationService notificationService;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtils jwtUtils;
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ApiResponse<Map<String, Object>> register(@RequestBody RegisterRequest request) {
        try {
            // 检查邮箱是否已存在
            if (userService.existsByEmail(request.getEmail())) {
                return ApiResponse.error("邮箱已被注册");
            }
            
            // 创建用户
            User user = new User();
            user.setEmail(request.getEmail());
            user.setPassword(passwordEncoder.encode(request.getPassword()));
            user.setNickname(request.getNickname());
            user.setPhone(request.getPhone());
            
            User savedUser = userService.save(user);
            
            // 生成JWT Token
            String token = jwtUtils.generateToken(
                savedUser.getId(), 
                savedUser.getEmail(), 
                savedUser.getRole().name()
            );
            
            // 发送欢迎邮件
            notificationService.pushWelcomeNotification(
                savedUser.getEmail(), 
                savedUser.getNickname()
            );
            
            Map<String, Object> result = new HashMap<>();
            result.put("user", savedUser);
            result.put("token", token);
            result.put("message", "注册成功");
            
            return ApiResponse.success(result);
            
        } catch (Exception e) {
            return ApiResponse.error("注册失败: " + e.getMessage());
        }
    }
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ApiResponse<Map<String, Object>> login(@RequestBody LoginRequest request) {
        try {
            User user = userService.findByEmail(request.getEmail());
            
            if (user == null) {
                return ApiResponse.error("用户不存在");
            }
            
            if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
                return ApiResponse.error("密码错误");
            }
            
            if (user.getStatus() != User.UserStatus.ACTIVE) {
                return ApiResponse.error("账号已被禁用");
            }
            
            // 生成JWT Token
            String token = jwtUtils.generateToken(
                user.getId(), 
                user.getEmail(), 
                user.getRole().name()
            );
            
            Map<String, Object> result = new HashMap<>();
            result.put("user", user);
            result.put("token", token);
            
            return ApiResponse.success(result);
            
        } catch (Exception e) {
            return ApiResponse.error("登录失败: " + e.getMessage());
        }
    }
    
    /**
     * 微信登录
     */
    @PostMapping("/wechat-login")
    public ApiResponse<Map<String, Object>> wechatLogin(@RequestBody Map<String, String> request) {
        try {
            String code = request.get("code");
            
            // 这里应该调用微信API获取openid，简化处理
            String openId = "wx_" + System.currentTimeMillis();
            
            User user = userService.findByWxOpenId(openId);
            
            if (user == null) {
                // 创建新用户
                user = new User();
                user.setWxOpenId(openId);
                user.setNickname("微信用户" + System.currentTimeMillis());
                user.setEmail(openId + "@wechat.com");
                user.setPassword(passwordEncoder.encode("123456"));
                user = userService.save(user);
            }
            
            // 生成JWT Token
            String token = jwtUtils.generateToken(
                user.getId(), 
                user.getEmail(), 
                user.getRole().name()
            );
            
            Map<String, Object> result = new HashMap<>();
            result.put("user", user);
            result.put("token", token);
            
            return ApiResponse.success(result);
            
        } catch (Exception e) {
            return ApiResponse.error("微信登录失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户信息
     */
    @GetMapping("/user-info")
    public ApiResponse<User> getUserInfo(@RequestParam Long userId) {
        User user = userService.findById(userId);
        if (user != null) {
            return ApiResponse.success(user);
        }
        return ApiResponse.error("用户不存在");
    }
    
    /**
     * 验证Token
     */
    @PostMapping("/validate")
    public ApiResponse<Map<String, Object>> validateToken(@RequestBody Map<String, String> request) {
        try {
            String token = request.get("token");
            
            if (token == null || token.isEmpty()) {
                return ApiResponse.error("Token不能为空");
            }
            
            boolean isValid = jwtUtils.validateToken(token);
            
            if (!isValid) {
                return ApiResponse.error("Token无效或已过期");
            }
            
            // 获取用户信息
            Long userId = jwtUtils.getUserIdFromToken(token);
            String email = jwtUtils.getEmailFromToken(token);
            String role = jwtUtils.getRoleFromToken(token);
            
            Map<String, Object> result = new HashMap<>();
            result.put("valid", true);
            result.put("userId", userId);
            result.put("email", email);
            result.put("role", role);
            
            return ApiResponse.success(result);
            
        } catch (Exception e) {
            return ApiResponse.error("Token验证失败: " + e.getMessage());
        }
    }
    
    /**
     * 刷新Token
     */
    @PostMapping("/refresh")
    public ApiResponse<Map<String, Object>> refreshToken(@RequestBody Map<String, String> request) {
        try {
            String token = request.get("token");
            
            if (token == null || token.isEmpty()) {
                return ApiResponse.error("Token不能为空");
            }
            
            if (!jwtUtils.validateToken(token)) {
                return ApiResponse.error("Token无效或已过期");
            }
            
            String newToken = jwtUtils.refreshToken(token);
            
            Map<String, Object> result = new HashMap<>();
            result.put("token", newToken);
            
            return ApiResponse.success(result);
            
        } catch (Exception e) {
            return ApiResponse.error("Token刷新失败: " + e.getMessage());
        }
    }
} 